﻿using System.Windows;
using System.Windows.Media;
using ICSharpCode.AvalonEdit.Editing;
using ICSharpCode.AvalonEdit.Rendering;
using Poet.ViewModels;

namespace Poet.Modules
{
    class SearchSelectionRender : IBackgroundRenderer
    {
        private readonly TextArea _textArea;

        public SearchSelectionRender(TextArea textArea, DocumentViewModel documentViewModel)
        {
            _textArea = textArea;
            _textArea.SelectionChanged +=
                (sender, args) =>
                    {
                        _textArea.Caret.Show();
                        _textArea.TextView.InvalidateLayer(KnownLayer.Background);
                    };
            _textArea.Caret.PositionChanged +=
                (sender, args) => _textArea.TextView.InvalidateLayer(KnownLayer.Background);
            documentViewModel.PropertyChanged += (sender, args) =>
                {
                    if (!Equals(args.PropertyName, "Matches")) return;
                    _textArea.TextView.InvalidateLayer(KnownLayer.Background);
                };
        }

        public KnownLayer Layer
        {
            get { return KnownLayer.Caret; }
        }

        public void Draw(TextView textView, DrawingContext drawingContext)
        {
            if (_textArea.Document == null || !_textArea.ShowCurrentLine)
                return;
 
            textView.EnsureVisualLines();
            foreach (var currentLine in textView.VisualLines)
            {
                foreach (var rect in BackgroundGeometryBuilder.GetRectsForSegment(textView, currentLine.FirstDocumentLine))
                {
                    drawingContext.DrawRectangle(
                        _textArea.CurrentLineBrush, _textArea.CurrentLineBorder,
                        new Rect(rect.Location, new Size(textView.ActualWidth + textView.ScrollOffset.X, rect.Height)));
                }
            }
        }
    }
}
